package com.servlet;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.utils.DBUtil;

/**
 * Servlet implementation class TestServlet
 */
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session=request.getSession(true);
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=\"UTF-8\"");
		response.setCharacterEncoding("UTF-8");
		Writer out = response.getWriter();
		System.out.println("servlet执行了...");
		if(!FileUpload.isMultipartContent(request)){
			System.out.println("进入了if");
			out.write("form的enctype属性值要为multipart/form-data");
			return;
		}
		
		//采用默认临界值和系统临时文件夹构造文件项工厂对象。配置上传参数
		DiskFileItemFactory factory=new DiskFileItemFactory();
		factory.setSizeThreshold(1024*1024*3); //设置内存临界值，超过后将产生临时文件并存储在临时目录中
		factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); //设置临时存储目录
		
		//实例化一个文件上传组件处理文件上传的核心类
		ServletFileUpload upload=new ServletFileUpload(factory);
		upload.setFileSizeMax(1024*1024*30); //设置上传文件的大小，以防止恶意传入很大的文件将磁盘沾满,其参数是以字节为单位的long型数字
		upload.setSizeMax(1024*1024*40); //设置请求消息实体内容的最大尺寸限制，以防止客户恶意上传超大文件来浪费服务器的存储空间
		
		String title=null;
		String content=null;
		File file=null;
		//获取HTTP请求消息内容进行解析的入口方法，解析出Form表单中的每个字段的数据，并将他们分别包装成独立的FileItem对象，然后将FileItem对象加入进一个List类型的集合对象中返回。
		try {
			List<FileItem> fileItem=upload.parseRequest(request);
			if(fileItem!=null&&fileItem.size()>0){
				for (FileItem item : fileItem) {
					String fields=item.getFieldName();
					String fileNa=item.getName();
					String files=item.getString();
					System.out.println("--"+fields+"\t"+files+"\t"+fileNa);
					if(!item.isFormField()){  //isFormField判断某项是否是一般表单类型
						String fileName=new File(item.getName()).getName();
						file=new File("c:/Users/cj/Desktop/upload/"+fileName);
						item.write(file);
						out.write("上传成功");
					}else{
						if("title".equals(item.getFieldName())){
							title=item.getString("UTF-8");
						}
						if("content".equals(item.getFieldName())){
							content = item.getString("UTF-8");
						}
					}
				}
				System.out.println(title+"\t"+content);
			}
			
			Connection conn=DBUtil.getConn();
			String sqlQuery="select userId from users where userName='"+session.getAttribute("name")+"'";
			Statement stm1=conn.createStatement();
			ResultSet rs=stm1.executeQuery(sqlQuery);
			rs.next();
			int userId=rs.getInt("userId");
			
			StringBuffer sql=new StringBuffer("insert into content (title,content,file,user_Id) values(");
			sql.append("'"+title+"',");
			sql.append("'"+content+"',");
			String filePath=file.getPath().replace('\\', '/'); 
			sql.append("'"+filePath+"',");
			sql.append("'"+userId+"')");
			System.out.println(sql.toString());
			System.out.println(title+"\t"+content+"\t"+filePath+"\t"+userId);
			Statement stm=conn.createStatement();
			stm.executeUpdate(sql.toString());
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
